package com.admin.system.security.service;

import com.admin.model.dto.UserDto;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.ObjectUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;

/**
 * @author caixiaofeng
 * @version 1.0
 * @Description: <<>>
 * @company 个人学习
 * @create 2021-02-03 21:45
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class UserDetailsImpl implements UserDetails {
    private UserDto user;
    private Set<GrantedAuthority> authorities;

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return authorities;
    }

    @JsonIgnore
    @Override
    public String getPassword() {
        return user.getPassword();
    }

    @JsonIgnore
    @Override
    public String getUsername() {
        return user.getUsername();
    }

    @JsonIgnore
    @Override
    public boolean isAccountNonExpired() {
        boolean expired = true;
        // 账户期限天数
        Integer expiredDays = user.getExpiredDays();
        //最后密码修改时间
        LocalDateTime resetTime = user.getPwdResetTime();
        if (!ObjectUtils.isEmpty(resetTime)) {
            //resetTime.plusDays(expiredDays);
            long pwdDay = resetTime.toLocalDate().toEpochDay();
            long currentDay = LocalDate.now().toEpochDay();
            long day = currentDay - pwdDay;
            if (day >= expiredDays) {
                expired = false;
            }
        }
        return expired;
    }

    @JsonIgnore
    @Override
    public boolean isAccountNonLocked() {
        return !user.getLocked();
    }

    @JsonIgnore
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @JsonIgnore
    @Override
    public boolean isEnabled() {
        return user.getEnabled();
    }
}
